package com.pactera.madp.cp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.admin.api.dto.WxDeptDto;
import com.pactera.madp.admin.api.entity.SysDept;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.security.util.SecurityUtils;
import com.pactera.madp.cp.api.constant.DeptConstants;
import com.pactera.madp.cp.api.dto.emp.WXDepartmentDTO;
import com.pactera.madp.cp.api.entity.CorpEntity;
import com.pactera.madp.cp.api.entity.WorkDeptEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeDepartmentEntity;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.feign.RemoteDeptService;
import com.pactera.madp.cp.api.vo.dept.DeptEmployeeLinkVO;
import com.pactera.madp.cp.api.vo.dept.DeptRecursionVo;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.WorkDeptMapper;
import com.pactera.madp.cp.service.ICorpService;
import com.pactera.madp.cp.service.IWorkDeptService;
import com.pactera.madp.cp.service.IWorkEmployeeDepartmentService;
import com.pactera.madp.cp.service.IWorkEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @description:部门表业务
 * @author: Huayu
 * @time: 2020/11/28 17:53
 */
@Service
public class WorkDeptServiceImpl extends ServiceImpl<WorkDeptMapper, WorkDeptEntity> implements IWorkDeptService {

    @Autowired
    @Lazy
    private IWorkEmployeeService workEmployeeService;
    @Autowired
    private IWorkEmployeeDepartmentService workEmployeeDepartmentService;
    @Autowired
    private ICorpService corpService;
    @Autowired
    private RemoteDeptService remoteDeptService;

    /**
     * @description:根据corpId获取部门
     * @return:
     * @author: Huayu
     * @time: 2020/11/28 18:00
     */
    @Override
    public List<WorkDeptEntity> getWorkDepartmentsByCorpId(String corpId) {
        QueryWrapper<WorkDeptEntity> entityQueryWrapper = new QueryWrapper<WorkDeptEntity>();
        entityQueryWrapper.setEntity(new WorkDeptEntity());
        entityQueryWrapper.eq("corp_id", corpId);
        return this.baseMapper.selectList(entityQueryWrapper);
    }


    @Override
    public boolean insertDeptments(List<WorkDeptEntity> workDeptEntityList,int corpId) {
        Integer i = 0;
        for (WorkDeptEntity dept : workDeptEntityList) {
            i = this.baseMapper.insert(dept);
        }
        if(i > 0){
            //处理父部门
            Map<String,Object> parentDeptMap = getDepartmentIds(corpId);
            List<WorkDeptEntity> workDeptEntityList1 = getDepartmentUpdateData(parentDeptMap);
            if(workDeptEntityList1 != null && workDeptEntityList1.size() > 0){
                updateWorkDepartmentByIds(workDeptEntityList1);
            }
        }
        return  true;
    }


    private void updateWorkDepartmentByIds(List<WorkDeptEntity> workDeptEntityList1) {
        for (WorkDeptEntity workDept:
        workDeptEntityList1) {
            UpdateWrapper<WorkDeptEntity> workDeptUpdateWrapper = new UpdateWrapper();
            workDeptUpdateWrapper.eq("id",workDept.getId());
            Integer i = this.baseMapper.update(workDept,workDeptUpdateWrapper);
            if(i < 1){
                log.error("WorkDeptService->handle>>>>>>>>同步部门失败");
            }
        }
    }


    private List<WorkDeptEntity> getDepartmentUpdateData(Map<String, Object> parentDeptMap) {
        List<WorkDeptEntity> workDeptEntityList = new ArrayList();
        for (String key : parentDeptMap.keySet()) {
            //级别
            WorkDeptEntity workDeptEntity = (WorkDeptEntity)parentDeptMap.get(key);
            Map map = getDepartmentRelation(workDeptEntity,parentDeptMap,"",0);
            WorkDeptEntity workDept = new WorkDeptEntity();
            workDept.setId(workDeptEntity.getId());
            workDept.setPath((String)map.get("path"));
            workDept.setLevel((Integer) map.get("level"));
            workDept.setParentId(parentDeptMap.get(workDeptEntity.getWxParentid().toString()) != null && !key.equals("0") ?((WorkDeptEntity)parentDeptMap.get(workDeptEntity.getWxParentid().toString())).getId() : 0);
            workDeptEntityList.add(workDept);
        }
        return workDeptEntityList;
    }


    private Map<String,Object> getDepartmentRelation(WorkDeptEntity workDeptEntity, Map<String, Object> parentDeptMap,String path,Integer level) {
        path = "#"+workDeptEntity.getId()+"#-"+path;
        if(!workDeptEntity.getWxParentid().toString().isEmpty() && !workDeptEntity.getWxParentid().toString().equals("0")){
            level = level + 1;
        }
        if(!workDeptEntity.getWxParentid().toString().isEmpty() && !workDeptEntity.getWxParentid().toString().equals("0")){
            return getDepartmentRelation((WorkDeptEntity)parentDeptMap.get(workDeptEntity.getWxParentid().toString()),parentDeptMap,path,level);
        }
        Map<String,Object> map = new HashMap();
        map.put("path",path.substring(0,path.length()-1));
        map.put("level",level);
        return map;
    }


    private Map<String, Object> getDepartmentIds(Integer corpId) {
        QueryWrapper<WorkDeptEntity> WorkDeptEntityWrapper = new QueryWrapper();
        WorkDeptEntityWrapper.getSqlSelect();
        WorkDeptEntityWrapper.eq("corp_id",corpId);
        Map<String,Object> map = new HashMap<String,Object>();
        List<WorkDeptEntity> parentDeptEntityList = this.baseMapper.selectList(WorkDeptEntityWrapper);
        for (WorkDeptEntity deptEntity : parentDeptEntityList) {
            map.put(deptEntity.getWxDepartmentId().toString(),deptEntity);
        }
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updDeptments(List<WorkDeptEntity> workDeptEntityList) {
        Integer i = 0;
        for (WorkDeptEntity dept :
                workDeptEntityList) {
            i = this.baseMapper.updateById(dept);
            i++;
        }
        return i;

    }

    /**
     * @description 部门管理 - 部门列表
     * @author zhaojinjian
     * @createTime 2021/1/7 12:54
     */
    @Override
    public JSONObject getWorkDepartments(String searchKeyWords, Integer corpId) {
        JSONObject resultJson = new JSONObject();
        QueryWrapper<WorkDeptEntity> deptWrapper = new QueryWrapper<>();
        if (searchKeyWords != null && !searchKeyWords.isEmpty()) {
            deptWrapper.like("name", searchKeyWords);
        }
        deptWrapper.eq("corp_id", corpId);
//        deptWrapper.isNull("deleted_at");
        List<WorkDeptEntity> deptList = this.list(deptWrapper);
        resultJson.put("department", this.getRecursionDeptList(deptList, 0));
        resultJson.put("employee", workEmployeeService.getCorpEmployeeName(corpId, searchKeyWords));
        return resultJson;
    }
    @Override
    public JSONObject getWorkDepartments1(String searchKeyWords, Integer corpId) {
        Integer sysDeptId = SecurityUtils.getUser().getDeptId();
        Integer wxDeptId = (Integer) remoteDeptService.getWxDeptId(sysDeptId).getData();
        JSONObject resultJson = new JSONObject();
        QueryWrapper<WorkDeptEntity> deptWrapper = new QueryWrapper<>();
        if (searchKeyWords != null && !searchKeyWords.isEmpty()) {
            deptWrapper.like("name", searchKeyWords);
        }
        deptWrapper.eq("corp_id", corpId);
//        deptWrapper.isNull("deleted_at");
        List<WorkDeptEntity> deptList = this.list(deptWrapper);
        resultJson.put("department", this.getRecursionDeptList1(deptList, wxDeptId));
        resultJson.put("employee", workEmployeeService.getCorpEmployeeName(corpId, searchKeyWords));
        return resultJson;
    }

    /**
     * @description 递归获取部门及子部门
     * @author zhaojinjian
     * @createTime 2021/1/7 12:55
     */
    private JSONArray getRecursionDeptList(List<WorkDeptEntity> list, Integer pId) {
        JSONArray resultArray = new JSONArray();
        List<WorkDeptEntity> childList = list.stream().filter(c -> c.getWxParentid() == pId).collect(Collectors.toList());
        childList.forEach(item -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", item.getId());
            jsonObject.put("name", item.getName());
            jsonObject.put("parentId", item.getParentId());
            jsonObject.put("son", this.getRecursionDeptList(list, item.getWxDepartmentId()));
            resultArray.add(jsonObject);
        });
        return resultArray;

    }
    private JSONArray getRecursionDeptList1(List<WorkDeptEntity> list, Integer pId) {
        JSONArray resultArray = new JSONArray();
        List<WorkDeptEntity> list1 = list.stream().filter(c -> c.getWxDepartmentId() == pId).collect(Collectors.toList());

//        List<WorkDeptEntity> childList = list.stream().filter(c -> c.getWxParentid() == pId).collect(Collectors.toList());
//        childList.forEach(item -> {
        list1.forEach(item -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", item.getId());
            jsonObject.put("name", item.getName());
            jsonObject.put("parentId", item.getParentId());
            jsonObject.put("son", this.getRecursionDeptList(list, item.getWxDepartmentId()));
            resultArray.add(jsonObject);
        });
        return resultArray;

    }

    public List getAllDept(List<WorkDeptEntity> depts, Integer pId) {
        ArrayList<DeptRecursionVo> vos = new ArrayList<>();
        List<WorkDeptEntity> childs = depts.stream().filter(f -> f.getParentId().equals(pId)).collect(Collectors.toList());
        childs.forEach(f -> {
            DeptRecursionVo vo = new DeptRecursionVo();
            List childs1 = getAllDept(depts, f.getId());
            vo.setChildDepts(childs1);
            vo.setName(f.getName());
            vo.setId(f.getId());
            vos.add(vo);
            depts.remove(f);
        });
        return vos;
    }

    /**
     * 递归获取所有部门
     * @return
     */
    @Override
    public List<DeptRecursionVo> getAllDepts() {


        List<WorkDeptEntity> depts = this.list(Wrappers.<WorkDeptEntity>query().eq("corp_id", CorpContextHolder.getCorpId()));

        List allDept = getAllDept(depts, 0);
        return allDept;
    }
    /**
     * @description 获取部门下的成员列表
     * @author zhaojinjian
     * @createTime 2021/1/7 13:32
     */
    @Override
    public JSONArray getDeptMemberList(List<Integer> deptIds, Integer corpId) {
        // 获取机构集合节点为根的所有森林节点机构集合
        deptIds = getChildrenAndGrandsons(deptIds).stream().collect(Collectors.toList());

        //region 获取成员和成员部门中间表信息
        List<WorkEmployeeDepartmentEntity> employeeDepartmentList = workEmployeeDepartmentService.getDeptEmployeeList(deptIds);
        List<Integer> empIds = employeeDepartmentList.stream().map(WorkEmployeeDepartmentEntity::getEmployeeId).collect(Collectors.toList());
        //endregion

        //region 获取部门信息
        QueryWrapper<WorkDeptEntity> workDeptWrapper = new QueryWrapper<>();
        workDeptWrapper.select("id,name");
        workDeptWrapper.in("id", deptIds);
//        workDeptWrapper.isNull("deleted_at");
        List<WorkDeptEntity> deptList = this.list(workDeptWrapper);
        //endregion

        //region 获取成员信息
        Map<Integer, String> empNameMap = workEmployeeService.getEmployeeName(corpId, empIds);
        //endregion
        JSONArray resultArray = new JSONArray();
        AtomicInteger count = new AtomicInteger();
        employeeDepartmentList.forEach(item -> {
            if (empNameMap.get(item.getEmployeeId()) != null){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("departmentId", item.getDepartmentId());
                Optional<WorkDeptEntity> deptOp = deptList.stream().filter(c -> c.getId().equals(item.getDepartmentId())).findAny();
                jsonObject.put("departmentName", deptOp.get().getName());
                jsonObject.put("employeeId", item.getEmployeeId());
                jsonObject.put("employeeName", deptOp.get().getName() + "--" + empNameMap.get(item.getEmployeeId()));
                resultArray.add(jsonObject);
            }
        });
        return resultArray;
    }



    @Override
    public List<WorkDeptEntity> getWorkDepartmentsById(String ids, String clStr) {
        QueryWrapper<WorkDeptEntity> workDeptEntityQueryWrapper = new QueryWrapper();
        workDeptEntityQueryWrapper.select(clStr);
        workDeptEntityQueryWrapper.in("id",ids);
        return this.baseMapper.selectList(workDeptEntityQueryWrapper);
    }

    @Override
    public List<WorkDeptEntity> getWorkDepartmentsByCorpIdName(Integer corpId, String name, String clStr) {
        QueryWrapper<WorkDeptEntity> workDeptEntityQueryWrapper = new QueryWrapper();
        workDeptEntityQueryWrapper.select(clStr);
        workDeptEntityQueryWrapper.eq("corp_id",corpId);
        if(name != null && !name.equals("")){
            workDeptEntityQueryWrapper.eq("name",name);
        }
        return this.baseMapper.selectList(workDeptEntityQueryWrapper);
    }

    @Override
    public List<WorkDeptEntity> getWorkDepartmentsByCorpIdPath(Integer corpId, String path, String id) {
        QueryWrapper<WorkDeptEntity> workDeptEntityQueryWrapper = new QueryWrapper();
        workDeptEntityQueryWrapper.select("id");
        workDeptEntityQueryWrapper.like("path",path);
        workDeptEntityQueryWrapper.eq("corp_id",corpId);
        return this.baseMapper.selectList(workDeptEntityQueryWrapper);
    }

    @Override
    public List<WorkDeptEntity> getWorkDepartmentsBySearch(String substring, String clStr) {
        List<WorkDeptEntity> workDeptEntityList = new ArrayList();
        String[] strArr = substring.split(",");
        for (String str:
        strArr) {
            QueryWrapper<WorkDeptEntity> workDeptEntityQueryWrapper = new QueryWrapper();
            workDeptEntityQueryWrapper.select(clStr);
            workDeptEntityQueryWrapper.eq("id",str);
            WorkDeptEntity workDeptEntity = this.baseMapper.selectOne(workDeptEntityQueryWrapper);
            workDeptEntityList.add(workDeptEntity);
        }
        return workDeptEntityList;
    }

    @Override
    public List<WorkDeptEntity> getWorkDepartmentsByPath(int level, String path) {
        QueryWrapper<WorkDeptEntity> workDeptEntityQueryWrapper = new QueryWrapper();
        workDeptEntityQueryWrapper.likeRight("path",path);
        //workDeptEntityQueryWrapper.eq("level",level);
        return this.baseMapper.selectList(workDeptEntityQueryWrapper);
    }

    /**
     * 根据部门 id 列表获取部门企业 id 列表
     *
     * @param deptIdList
     */
    @Override
    public List<Integer> getWxDeptIdListByDeptIdList(List<Integer> deptIdList) {
        if (Objects.isNull(deptIdList) || deptIdList.isEmpty()) {
            return Collections.emptyList();
        }

        return listByIds(deptIdList).stream().map(WorkDeptEntity::getWxDepartmentId).collect(Collectors.toList());
    }

    @Override
    public List<WorkDeptEntity> getNameById(String departmentIds, String name) {
        QueryWrapper<WorkDeptEntity> workDeptEntityQueryWrapper = new QueryWrapper();
        workDeptEntityQueryWrapper.select(name);
        workDeptEntityQueryWrapper.in("id",departmentIds);
        return this.baseMapper.selectList(workDeptEntityQueryWrapper);
    }
    //lllllllllllll

    @Override
    public List<Integer> getAllChilds(Integer deptId) {
        QueryWrapper<WorkDeptEntity> wrapper = new QueryWrapper<>();
        Integer level = getObj(wrapper.select("level").eq("id", deptId), (o -> {
            return Integer.parseInt(o.toString());
        }));
        ArrayList<Integer> ids = new ArrayList<>();
        ids.add(deptId);
        List<WorkDeptEntity> deptEntities = this.query().select("id, parent_id").gt("level", level).eq("corp_id", CorpContextHolder.getCorpId()).list();
        deptEntities.forEach(f -> {
            deptEntities.forEach(entity -> {
                if (ids.contains(entity.getParentId())) ids.add(entity.getId());
            });
        });
        return ids.stream().distinct().collect(Collectors.toList());
    }
    @Override
    public List<Integer> getAllAllowChilds(List<Integer> deptIds) {
        ArrayList<Integer> reIds = new ArrayList<>();
        List<Integer> ids = listObjs(Wrappers.<WorkDeptEntity>lambdaQuery().select(WorkDeptEntity::getId).in(WorkDeptEntity::getWxDepartmentId, deptIds), o -> Integer.parseInt(o.toString()));
        ids.forEach(f -> {
            reIds.addAll(getAllChilds(f));
        });
        return reIds.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public R<Integer> createDept(WxDeptDto dto) {
        //创建企业微信部门
        Integer corpId = getCorpId();
        String id = WxApiUtils.requestDepartmentCreateApi(corpId, JSONUtil.toJsonStr(dto));
        if(StrUtil.isEmpty(id)) {
            throw new CheckedException("企业微信部门创建失败");
        }

        //同步系统企业微信部门表
        String result = WxApiUtils.requestDepartmentListApi(corpId, Integer.valueOf(id));
        List<WXDepartmentDTO> depts = JSONUtil.toList(JSONUtil.parseArray(result),WXDepartmentDTO.class);
        WXDepartmentDTO wxDepartmentDTO = depts.get(0);

        WorkDeptEntity entity = new WorkDeptEntity();
        entity.setWxDepartmentId(wxDepartmentDTO.getId());
        entity.setCorpId(corpId);
        entity.setName(wxDepartmentDTO.getName());
        entity.setParentId(workEmployeeService.getMainDepartmentId(corpId, wxDepartmentDTO.getParentid()));
        entity.setWxParentid(wxDepartmentDTO.getParentid());
        entity.setOrder(wxDepartmentDTO.getOrder());

        List<WorkDeptEntity> workDeptEntityList = new ArrayList<>();
        workDeptEntityList.add(entity);
        this.insertDeptments(workDeptEntityList,corpId);

        //返回生成的企业微信部门id
        return R.ok(Integer.valueOf(id));
    }

    @Override
    public R<Boolean> updateDept(WxDeptDto dto) {
        //更新企业微信部门
        Integer corpId = getCorpId();
        String errcode = WxApiUtils.requestDepartmentUpdateApi(corpId, JSONUtil.toJsonStr(dto));
        if(!"0".equals(errcode)) {
            throw new CheckedException("企业微信部门修改失败");
        }
        WorkDeptEntity workDeptEntity = this.getOne(Wrappers.<WorkDeptEntity>lambdaQuery().eq(WorkDeptEntity::getWxDepartmentId,dto.getId()));
        workDeptEntity.setName(dto.getName());
        workDeptEntity.setOrder(dto.getOrder());
        this.updateById(workDeptEntity);

        return R.ok(true);
    }

    @Override
    public R<Boolean> deleteDept(Integer wxDeptId) {
        //删除企业微信部门
        Integer corpId = getCorpId();
        String errcode = WxApiUtils.requestDepartmentDeleteApi(corpId, wxDeptId);
        if(!"0".equals(errcode)) {
            throw new CheckedException("企业微信部门删除失败");
        }
        WorkDeptEntity workDeptEntity = this.getOne(Wrappers.<WorkDeptEntity>lambdaQuery()
                .eq(WorkDeptEntity::getWxDepartmentId,wxDeptId));

        //同步删除系统企业微信部门
        return R.ok(this.remove(Wrappers.<WorkDeptEntity>lambdaQuery(workDeptEntity)));
    }

    @Override
    public DeptEmployeeLinkVO getLinkObjects(Integer deptId) {
        DeptEmployeeLinkVO vo = new DeptEmployeeLinkVO();
        ArrayList<DeptEmployeeLinkVO.LinkObject>  linkObjects= new ArrayList<>();
        R r1 = remoteDeptService.getWxDeptId(SecurityUtils.getUser().getDeptId());
        //当前登录用户的机构
        WorkDeptEntity currentLogDept = this.getOne(new LambdaQueryWrapper<WorkDeptEntity>()
                .eq(WorkDeptEntity::getWxDepartmentId, r1.getData()));
        vo.setCurrentLogUserDeptLevel(currentLogDept.getLevel());

        R r2 = remoteDeptService.getWxDeptId(deptId);
        //查询的机构
        WorkDeptEntity queryDept = this.getOne(new LambdaQueryWrapper<WorkDeptEntity>()
                .eq(WorkDeptEntity::getWxDepartmentId, r2.getData()));
        if (queryDept.getLevel() < DeptConstants.SUB_BRANCH_LEVEL) {
            //返回下级机构列表
            Object data = remoteDeptService.getLowerDepts(deptId).getData();
            JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(data));
            if (!jsonArray.isEmpty()) {
                jsonArray.forEach(j->{
                    SysDept dept = JSON.parseObject(j.toString(), SysDept.class);
                    DeptEmployeeLinkVO.LinkObject linkObject = new DeptEmployeeLinkVO.LinkObject();
                    linkObject.setObjectId(dept.getDeptId());
                    linkObject.setObjectName(dept.getName());
                    linkObjects.add(linkObject);
                });
            }
            vo.setLinkObjects(linkObjects);
        } else {
            //返回成员列表
            List<Integer> employeeIds = workEmployeeDepartmentService.list(new LambdaQueryWrapper<WorkEmployeeDepartmentEntity>()
                    .eq(WorkEmployeeDepartmentEntity::getDepartmentId, queryDept.getId()))
                    .stream()
                    .map(WorkEmployeeDepartmentEntity::getEmployeeId)
                    .collect(Collectors.toList());
            if (!employeeIds.isEmpty()) {
                Collection<WorkEmployeeEntity> employees = workEmployeeService.listByIds(employeeIds);
                employees.forEach(e->{
                    DeptEmployeeLinkVO.LinkObject linkObject = new DeptEmployeeLinkVO.LinkObject();
                    linkObject.setObjectId(e.getId());
                    linkObject.setObjectName(e.getName());
                    linkObjects.add(linkObject);
                });
            }
            vo.setLinkObjects(linkObjects);
        }
        return vo;
    }

    /**
     * 获取企业
     * @return
     */
    private Integer getCorpId() {
        List<CorpEntity> list = corpService.list();
        if (list.isEmpty()) {
            throw new CheckedException("企业不存在");
        }
        return list.get(0).getCorpId();
    }

    /**
     * 同步系统企业微信部门
     * @param corpId
     */
    @Async
    protected void syncDepartment(int corpId) {
        workEmployeeService.syncDepartment(corpId);
    }

    private Set<Integer> getChildrenAndGrandsons(List<Integer> deptIds) {
        Set<Integer> allDeptIds = new HashSet<>();
        for (Integer deptId : deptIds) {
            WorkDeptEntity workDeptEntity = this.baseMapper.selectOne(
                    Wrappers.<WorkDeptEntity>lambdaQuery()
                    .select(WorkDeptEntity::getLevel, WorkDeptEntity::getId)
                    .eq(WorkDeptEntity::getId, deptId)
            );
            getChildrens(workDeptEntity, allDeptIds);
        }
        return allDeptIds;
    }

    private void getChildrens(WorkDeptEntity workDeptEntity, Set<Integer> allDeptIds) {
        Integer deptId = workDeptEntity.getId();
//        if (level == 3) {
//            allDeptIds.add(deptId);
//        } else if (level < 3) {
//            List<WorkDeptEntity> childrens = this.baseMapper.selectList(
//                    Wrappers.<WorkDeptEntity>lambdaQuery()
//                            .select(WorkDeptEntity::getLevel, WorkDeptEntity::getLevel)
//                            .eq(WorkDeptEntity::getParentId, deptId)
//            );
//            for (WorkDeptEntity entity: childrens) {
//                getChildrens(entity, allDeptIds);
//            }
//        }
        allDeptIds.add(deptId);
        List<WorkDeptEntity> childrens = this.baseMapper.selectList(
                Wrappers.<WorkDeptEntity>lambdaQuery()
                        .select(WorkDeptEntity::getId, WorkDeptEntity::getLevel)
                        .eq(WorkDeptEntity::getParentId, deptId)
        );
        for (WorkDeptEntity entity: childrens) {
            getChildrens(entity, allDeptIds);
        }
    }
}
